<template>
  <div>
    <!--面包屑功能-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区-->
    <el-card>
      <!--搜索区-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="readUserList">
            <el-button slot="append" icon="el-icon-search"
             @click="readUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="openuser">添加用户</el-button>
        </el-col>
      </el-row>
      <!--表格区-->
      <el-table :data="userlist" :border="true" style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="id" label="编号" width="80"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="地址" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!--修改-->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserDialogShow(scope.row.id)"
            ></el-button>
            <!--删除-->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!--设置角色-->
            <el-tooltip
              content="设置角色"
              placement="top"
              :enterable="false"
              effect="dark"
            >
              <el-button
                type="warning"
                icon="el-icon-paperclip"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 50, 100, 200]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!--增加对话框区-->
    <el-dialog
    title="增加用户"
    :visible.sync="addDialogVisible"
    width="50%" @close="addDialogClose">
    <!--对话框内容区-->
    <el-form :model="addUserForm" :rules="addUserrules"
    ref="addFormRef"
     label-width="70px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addUserForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addUserForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addUserForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="addUserForm.phone"></el-input>
      </el-form-item>
    </el-form>

    <!--对话框按钮区-->
    <span slot="footer" class="dialog-footer">
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
    </el-dialog>
    <!--制作修改对话框部分start-->
    <el-dialog
      title="修改用户"
      :visible.sync="edidUsedialogVisible"
      width="100">
      <!--修改内容区-->
      <el-form :model="editUserForm" :rules="editUserRules"
      ref="editRuleFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" readonly disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!--修改按钮区-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDailogClose">取 消</el-button>
        <el-button type="primary" @click="editUserSave">确 定</el-button>
      </span>
    </el-dialog>
    <!--制作修改对话框部分end-->
  </div>
</template>

<script>
export default {
  // 数据定义区
  data() {
    // 检查邮箱的验证
    const checkemail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 检查手机号验证的自定义验证
    const checkphone = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      userlist: [], // 数据列表集合
      total: 0, // 总数据条数
      addDialogVisible: false, // 增加对话框显示与隐藏
      // 表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      // 表单验证数据
      addUserrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' }
        ]
      },
      // 修改对话框 显示与隐藏标识
      edidUsedialogVisible: false,
      // 要修改数据对象
      editUserForm: {
        id: 0,
        username: '',
        mobile: '',
        email: ''
      },
      // 修改用户数据验证部分
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' }
        ]
      }
    }
  },
  // 方法定义区
  methods: {
    async readUserList() {
      // 读数据方法
      // 注意一定get 加上参数名
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.totalpage
    },
    // 每一页多少条改变事件,参数每页多少条
    handleSizeChange: function (val) {
      this.queryInfo.pagesize = val // 设置新的每页条数
      this.readUserList() // 再访问服务端
    },
    // 当前页码选中改变事件,参数为当前页
    handleCurrentChange: function (val) {
      this.queryInfo.pagenum = val
      this.readUserList()
    },
    // 开关按钮选项事件 参数为行上绑定的对象
    async userStateChanged(obj) {
      console.log(obj)
      // put / post 请求简单参数数据
      const { data: res } = await this.$http.put(`users/${obj.id}/state/${obj.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        // 重置到原来的状态
        obj.mg_state = !obj.mg_state
        return this.$message.error('改变状态失败')
      }
      this.$message.success('改变状态成功')
    },
    // 打开增加对话框
    openuser() {
      this.addDialogVisible = true
    },
    // 关闭对话框执行功能
    addDialogClose() {
      // 获取对话框中表单的引用
      this.$refs.addFormRef.resetFields()
    },
    // 对话框，确定按钮功能
    addUser() {
      // 先预验证
      this.$refs.addFormRef.validate(async valid => {
        // eslint-disable-next-line no-useless-return
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('增加出错')
        this.$message.success('增加成功')
        // 隐藏
        this.addDialogVisible = false
        // 表格加数据
        this.readUserList()
      })
    },
    // 行上的修改点击后 显示
    async editUserDialogShow(id) {
      // 显示id
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据出错')
      }
      this.editUserForm = res.data
      // 显示修改对话框
      this.edidUsedialogVisible = true
    },
    // 修改对话框中的关闭按钮触发执行方法
    editUserDailogClose() {
      // 获取到表单引用对象并重置
      this.$refs.editRuleFormRef.resetFields()
      // 关闭窗口
      this.edidUsedialogVisible = false
    },
    // 修改确定按钮，执行功能
    editUserSave() {
      this.$refs.editRuleFormRef.validate(async valid => {
        // 验证不通过
        if (!valid) return
        // 调用异步功能
        const { data: res } = await this.$http.put('users/' + this.editUserForm.id, this.editUserForm)
        if (res.meta.status !== 200) return this.$message.error('修改出错')
        this.$message.success('修改成功')
        // 成功后刷新
        this.readUserList()
        // 关闭窗口
        this.edidUsedialogVisible = false
      })
    },
    // 删除按钮对应功能
    async deleteUser(id) {
      // 先弹出提示
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      console.log(res)
      // 取消res 为 cancel  确定为confirm
      if (res === 'cancel') return this.$message.info('已取消删除')
      // ajax
      const { data: rdata } = await this.$http.delete('users/' + id)
      if (rdata.meta.status !== 200) return this.$message.error('删除出错')
      this.$message.error('删除正确')
      // 刷新数据
      this.readUserList()
    }
  },
  // 周期,加载事件
  mounted() {
    this.readUserList() // 加载调用读取数据
  }
}
</script>

<style lang="less" scoped>
</style>
